package com.lzh.tiktok.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzh.common.utils.JwtUtils;
import com.lzh.tiktok.user.dao.UserDao;
import com.lzh.tiktok.user.entity.UserEntity;
import com.lzh.tiktok.user.exception.UsernameExistException;
import com.lzh.tiktok.user.service.FollowService;
import com.lzh.tiktok.user.service.UserService;
import com.lzh.tiktok.user.vo.UserResponseVo;
import com.lzh.tiktok.user.vo.UserVo;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author lizhihang
 * @create 2023-01-16 20:09
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
    @Autowired
    UserDao userDao;
    @Autowired
    FollowService followService;

    /**
     * 注册
     *
     * @param username 账号
     * @param password 密码
     * @return
     */
    @Override
    @Transactional
    public UserEntity register(String username, String password) throws UsernameExistException {
        UserDao userDao = this.baseMapper;
        UserEntity userEntity = new UserEntity();
        //检查用户名是否重复
        Boolean isReputly = checkUsernameUnique(username);
        if (isReputly) {
            //todo 返回特定的异常
            throw new UsernameExistException();
        }
        userEntity.setUsername(username);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(password);
        userEntity.setPassword(encode);
        //插入User表
        userDao.insert(userEntity);
        return userEntity;
    }

    @Override
    public UserEntity login(String username, String password) {
        //1、去数据库中查询是否有此账号
        //select count(*) from `user` where username=?
        UserDao userDao = this.baseMapper;
        UserEntity userEntity = userDao.selectOne(new QueryWrapper<UserEntity>()
                .eq("username", username));
        if (userEntity == null) {
            //账号错误
            return null;
        } else {
            //判断密码是否匹配
            String passwordDb = userEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //密码匹配
            boolean matches = passwordEncoder.matches(password, passwordDb);
            if (matches) {
                //用户名密码匹配
                return userEntity;
            } else {
                //用户名密码不匹配
                return null;
            }
        }
    }

    /**
     * @param userId 当前查看用户信息页面的用户id
     * @param token  当前登录者的用户id
     * @return
     */
    @Override
    public UserVo getUserInfo(Integer userId, String token) {
        UserEntity userEntity = userDao.selectById(userId);
        UserVo userVo = new UserVo();
        userVo.setId(userEntity.getUserId());
        userVo.setName(userEntity.getUsername());
        //关注博主数量
        Integer followCount = followService.getFollowCountByUserId(userId);
        userVo.setFollow_count(followCount);
        //粉丝数量
        Integer followerCount = followService.getFollowerByUserId(userId);
        userVo.setFollower_count(followerCount);
        //设置是否关注当前主页的人
        //如果当前是查看的自己的信息，不用设置是否关注自己
        if (JwtUtils.getUserId(token).equals(userId)) {

        } else {
            //todo 当前查看的是别人的页面 去数据库查询是否关注了此人
            Boolean isFollowed = followService.isFollowed(userId, token);
            userVo.setIs_follow(isFollowed);
        }
        return userVo;
    }

    /**
     * @param username
     * @return 重复返回true，不重复返回false
     */
    private Boolean checkUsernameUnique(String username) {
        //select count(*) from `users` where username = username
        Integer count = new Integer(0);
        try {
            count = userDao.queryIsExist(username);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (count == 1) {
            //重复返回true
            return true;
        }
        //不重复返回false
        return false;
    }

}
